package com.example.fengyungo_user.utils;

import static android.content.Context.MODE_PRIVATE;

import android.app.Service;
import android.content.SharedPreferences;

import androidx.fragment.app.FragmentActivity;

import com.example.fengyungo_user.constant.ResultConstant;
import com.example.fengyungo_user.constant.UserConstant;
import com.example.fengyungo_user.domain.User;

public class SharedPreferencesUtils {
    /**
     * 在FragmentActivity获取当前用户的信息
     *
     * @return Driver
     */
    public static User getUserInfo(FragmentActivity fragmentActivity) {
        // 从SharedPreferences中获取信息
        SharedPreferences preferences = fragmentActivity.getSharedPreferences(UserConstant.SP_NAME, MODE_PRIVATE);

        User user = parseUser(preferences);

        return user;
    }

    /**
     * 从SharedPreferences中获取用户信息
     * @param preferences SharedPreferences
     * @return User
     */
    private static User parseUser(SharedPreferences preferences) {
        String id = preferences.getString(UserConstant.ID, "");
        String avatar = preferences.getString(UserConstant.AVATAR, "");
        String nickname = preferences.getString(UserConstant.NICKNAME, "未设置");
        String username = preferences.getString(UserConstant.USERNAME, "123456");
        String sex = preferences.getString(UserConstant.SEX, "未设置");
        String phone = preferences.getString(UserConstant.PHONE, "未设置");
        String mail = preferences.getString(UserConstant.MAIL, "未设置");
        String password = preferences.getString(UserConstant.PASSWORD, "");
        Integer status = preferences.getInt(UserConstant.STATUS, 0);
        String createTime = preferences.getString(UserConstant.CREATE_TIME, "");
        String idCard = preferences.getString(UserConstant.ID_CARD, "");

        User user = new User();
        user.setUserId(id);
        user.setUserNickname(nickname);
        user.setUserUsername(username);
        user.setUserSex(sex);
        user.setUserPhone(phone);
        user.setUserPassword(password);
        user.setUserIdCard(idCard);
        user.setUserAvatar(avatar);
        user.setUserStatus(status);
        user.setUserCreateTime(createTime);
        user.setUserMail(mail);

        return user;
    }

    /**
     * 在服务中获取当前用户的信息
     * @param service Service
     * @return Driver
     */
    public static User getUserInfoInService(Service service) {
        // 从SharedPreferences中获取信息
        SharedPreferences preferences = service.getSharedPreferences(ResultConstant.DATA, MODE_PRIVATE);

        User user = parseUser(preferences);

        return user;
    }

}
